import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter,
  ElementRef
} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { AppComponentBase } from '@shared/common/app-component-base';

import * as moment from 'moment';
import { finalize } from 'rxjs/operators';
import {
  MainTaskServiceProxy,
  TaskDto,
  MainTaskGoProductionDto,
  NameValueDtoOfNameValueDto,
  PipelineServiceProxy,
  SideTaskServiceProxy
} from '@shared/service-proxies/service-proxies';

@Component({
  selector: 'putIntoProductionModal',
  styleUrls: ['./put-into-production-modal.component.less'],
  templateUrl: './put-into-production-modal.component.html'
})
export class PutIntoProductionModalComponent extends AppComponentBase {
  @ViewChild('actionModal') modal: ModalDirective;
  @ViewChild('dueDatePicker') dueDatePicker: ElementRef;
  @ViewChild('tmplCombobox') tmplCombobox: ElementRef;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  tmpls: NameValueDtoOfNameValueDto[];
  //投产数量
  amount: number = undefined;
  dueDate = new Date(); //moment.Moment = undefined;
  order: TaskDto = new TaskDto();
  tmplName = '';

  taskType = 1;

  constructor(
    injector: Injector,
    private _mainTaskServiceProxy: MainTaskServiceProxy,
    private _sideTaskServiceProxy: SideTaskServiceProxy,
    private _pipelineService: PipelineServiceProxy
  ) {
    super(injector);
  }

  show(order: TaskDto, taskType = 1): void {
    this.amount = 1;

    this.active = true;

    this.order = order;

    this.taskType = taskType;

    this._pipelineService.getPipelineTmpls().subscribe(result => {
      this.tmpls = result.items;

      // setTimeout(() => {
      //   this.tmplCombobox.nativeElement.selectpicker('refresh');
      // }, 0);

      this.modal.show();
    });
  }

  save(): void {
    this.saving = true;
    let input = new MainTaskGoProductionDto();
    input.quantity = this.amount;
    input.pipeTmplName = this.tmplName;
    input.comTime = moment(this.dueDate);
    input.id = this.order.id;

    if (this.taskType === 1) {
      this._mainTaskServiceProxy
        .goProduction(input)
        .pipe(
          finalize(() => {
            //this.close();
            this.saving = false;
          })
        )
        .subscribe(result => {
          this.notify.info('投产成功');
          this.close();
          this.modalSave.emit(this.order);
        });
    } else {
      this._sideTaskServiceProxy
        .goProduction(input)
        .pipe(
          finalize(() => {
            //this.close();
            this.saving = false;
          })
        )
        .subscribe(result => {
          this.notify.info('投产成功');
          this.close();
          this.modalSave.emit(this.order);
        });
    }
  }

  close(): void {
    this.saving = false;
    this.modal.hide();
  }
}
